package com.azdebugit.trancation.test.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    /**
     * MD5加密操作
     *
     * @param string
     */
    public static String msgToMD5(String string) {
        StringBuilder sb = new StringBuilder();
        try {
            //获取数据摘要器
            //参数：加密的方式
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            //摘要数据
            //参数：将要加密的明文转成byte数组
            byte[] digest = messageDigest.digest(string.getBytes());
            //加密操作
            for (int i = 0; i < digest.length; i++) {
                //MD5加密的核心原理：将一个byte数组通过与int类型进&运算得到一个int类型的正整数
                int result = digest[i] & 0xff;
                //可能得到的int数据会造成MD%加密的密文比较长，所以进行一个16进制的转换
                String hexString = Integer.toHexString(result);
                if (hexString.length() < 2) {
                    sb.append("0");
                }
                sb.append(hexString);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return string;
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

}